// stores/admin.js
import { defineStore } from 'pinia'

export const useAdminStore = defineStore('user', {
  state: () => ({
    user: null,
    token: null
  }),
  actions: {
    setUser(userData) {
      this.user = userData
    },
    setToken(token) {
      this.token = token
    },
    logout() {
      this.user = null
      this.token = null
      localStorage.removeItem('adminToken')
      localStorage.removeItem('adminUserInfo')
    },
    // 更新用户信息
    updateUserInfo(userData) {
      this.user = { ...this.user, ...userData }
    },
    // 初始化store，从localStorage恢复数据
    initializeStore() {
      const token = localStorage.getItem('adminToken')
      const userInfo = localStorage.getItem('adminUserInfo')
      
      if (token && userInfo) {
        try {
          this.token = token
          this.user = JSON.parse(userInfo)
        } catch (error) {
          console.error('恢复用户信息失败:', error)
          this.logout()
        }
      }
    }
  },
  getters: {
    isAdmin: (state) => state.user?.roleTypes?.includes('admin') || state.user?.roles?.includes('admin'),
    userName: (state) => state.user?.userName || state.user?.name || '用户',
    userEmail: (state) => state.user?.email || '',
    userPhone: (state) => state.user?.phoneNumber || '',
    userAvatar: (state) => state.user?.avatarUrl || '',
    userId: (state) => state.user?.id || '',
    userStatus: (state) => state.user?.status || 'active',
    userRoles: (state) => state.user?.roles || state.user?.roleTypes || []
  }
})